const express = require("express");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../../model/user");
const Music = require("../../model/music");
const News = require("../../model/news");
const Share = require("../../model/share");
const { secret } = require("../../config/key");
const date = require("silly-datetime");

const router = express.Router({
    //合并url参数，使其能被req.params访问到
    mergeParams: true,
});
//验证身份-中间件
const isUser = async (req, res, next) => {
    //jwt,取Bearer后面的值
    if (!req.headers.authorization) {
        res.status(422).send("未传入token");
    } else {
        const token = req.headers.authorization.split(" ").pop();
        try {
            const { _id, username } = jwt.verify(token, secret);
            if (_id) {
                req._id = _id;
                // 查询用户id是否存在
                const user = await User.findById(_id);
                if (!user) {
                    return res.status(422).send("用户错误");
                }
                //用户存在，查看username
                if (username !== user.username) {
                    res.status(422).send("用户错误");
                } else {
                    next();
                }
            } else {
                return res.status(422).send("用户错误");
            }
        } catch (err) {
            return res.status(422).send("用户错误");
        }
    }
};

// 读取用户信息
router.get("/read", isUser, async (req, res) => {
    // 查询用户名是否存在
    const user = await User.findById(req._id);
    const { username,musiclikes,peoplelikes} = user;
    res.send({username,musiclikes,peoplelikes});
});

//获取用户列表
router.get("/", isUser, async (req, res) => {
    // res.send("hello UserRouter")
    const list = await User.find();
    res.send(list);
});

// 保存喜爱的歌曲
router.post("/music/store", isUser, async (req, res) => {
    await User.findByIdAndUpdate(req._id, req.body);
    let music = await User.findById(req._id).populate("musiclikes"); 
    res.send(music.musiclikes);
});

// 保存关注的人
router.post("/people/store", isUser, async (req, res) => {
    await User.findByIdAndUpdate(req._id, req.body);
    let people = await User.findById(req._id).populate({ path: "peoplelikes" });
    let ids = people.peoplelikes.map(i => i._id)
    res.send(ids);
});

//分享歌曲或文章初始化
router.get("/share/:id", isUser, async (req, res) => {
    let id = req.params.id
    let data = {}
    data = await Music.findById(id)
    if (data) {
    } else {
        data = await News.findById(id)
    }
    res.send(data)
})

// 分享歌曲或者文章
router.post("/share", isUser, async (req, res) => {
    const dateTime = date.format(new Date(), 'YYYY.MM.DD');
    let params = {
        user_id: req._id,
        content: req.body.content,
        dateTime
    }
    let obj
    let music = await Music.findById(req.body.id)
    if (music) {
        let music_id = req.body.id
        obj = Object.assign({}, { music_id }, params)
    } else {
        let news_id = req.body.id
        obj = Object.assign({}, { news_id }, params)
    }
    const shareMusic = await new Share(obj).save();
    res.send(shareMusic)
});

// 取消喜爱的歌曲
router.delete("/music/dislike/:id", isUser, async (req, res) => {
    let music = await User.updateOne({ _id: req._id }, { $pull: { musiclikes: req.params.id } });
    // await User.findOneAndUpdate(req._id, req.body);
    res.send(music);
});

// 取消关注的人
router.delete("/people/dislike/:id", isUser, async (req, res) => {
    let people = await User.updateOne({ _id: req._id }, { $pull: { peoplelikes: req.params.id } });
    res.send(people);
});

// 注册
router.post("/register", async (req, res) => {
    //判断用户名是否存在
    const user = await User.findOne({ username: req.body.username });
    if (user) {
        return res.status(409).send("该用户已存在");
    }
    const newUser = await new User(req.body).save();
    res.send(newUser);
});

// 登录
router.post("/login", async (req, res) => {
    // 查询用户名是否存在
    const user = await User.findOne({ username: req.body.username });
    if (!user) {
        return res.status(422).send("该用户不存在");
    }
    let isPassword = await bcrypt.compareSync(req.body.password, user.password);
    if (!isPassword) {
        return res.status(422).send("密码错误");
    }
    const { _id, username } = user;
    //token 加密
    const token = jwt.sign({ _id, username }, secret, { expiresIn: "24h" });
    res.send(token);
});

module.exports = router;
